package cn.tjad.tjad2.module.main.activity;

import android.Manifest;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Process;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.MenuItem;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.qiandian.android.base.activity.BaseActivity;
import com.qiandian.android.base.common.bean.CommonBean;
import com.qiandian.android.base.common.utils.JsonUtils;
import com.qiandian.android.base.net.http.HttpConstants;
import com.qiandian.android.base.net.http.IDataCallBack;

import java.util.ArrayList;
import java.util.List;

import cn.tjad.tjad2.AppStartService;
import cn.tjad.tjad2.R;
import cn.tjad.tjad2.application.TjadApplication;
import cn.tjad.tjad2.business.RemoteDataService;
import cn.tjad.tjad2.consts.Keys;
import cn.tjad.tjad2.data.bean.PageMenu;
import cn.tjad.tjad2.data.bean.User;
import cn.tjad.tjad2.module.design.fragment.DesignTabFragment;
import cn.tjad.tjad2.module.document.fragment.DocumentFragment;
import cn.tjad.tjad2.module.common.fragment.FragmentContainer;
import cn.tjad.tjad2.module.user.fragment.SettingFragment;
import cn.tjad.tjad2.module.backhandle.BackHandlerHelper;
import cn.tjad.tjad2.receiver.NetworkStatusReceiver;
import cn.tjad.tjad2.route.PageId;
import cn.tjad.tjad2.utils.BottomNavigationViewHelper;
import cn.tjad.tjad2.utils.ConfigReader;
import cn.tjad.tjad2.utils.ExitAppManager;
import cn.tjad.tjad2.utils.RouteUtils;
import cn.tjad.tjad2.utils.Tools;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
import pub.devrel.easypermissions.PermissionRequest;

@Route(path = PageId.MAIN)
public class MainActivity extends BaseActivity implements ExitAppManager.OnExitAppTriggerListener {

    private List<Fragment> fragmentList;
    private FragmentManager fragmentManager;

    private Fragment currentDisplayFragment;
    private ExitAppManager exitAppManager;

    private NetworkStatusReceiver networkStatusReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        exitAppManager = new ExitAppManager();
        exitAppManager.setOnExitAppTriggerListener(this);
        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
        BottomNavigationViewHelper.disableShiftMode(navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
        initFragments();
        fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.add(R.id.fragment_container, fragmentList.get(0));
        transaction.commitAllowingStateLoss();
        currentDisplayFragment = fragmentList.get(0);
        registerNetworkReceiver();
        checkPermissions();
        requestUserInfo();

    }

    @Override
    protected boolean showTitle() {
        return false;
    }

    @Override
    protected void onStart() {
        super.onStart();
//        if (!EasyPermissions.hasPermissions(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
//            EasyPermissions.requestPermissions(
//                    new PermissionRequest.Builder(this, 1001, Manifest.permission.READ_EXTERNAL_STORAGE)
//                            .build()
//            );
//        }
    }

    private void checkPermissions() {
        List<String> permissionList = new ArrayList<>();
        permissionList.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        if (EasyPermissions.hasPermissions(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
            startAppService();
        } else if (EasyPermissions.somePermissionPermanentlyDenied(this, permissionList)) {
                new AppSettingsDialog.Builder(this)
                        .setTitle("权限已关闭")
                        .setRationale("" + "您已关闭了文件读取权限，必须要打开该权限才能使用该功能，是否前往打开？")
                        .build().show();
        } else {
            EasyPermissions.requestPermissions(
                    new PermissionRequest.Builder(this, 1001, Manifest.permission.READ_EXTERNAL_STORAGE)
                            .build()
            );
        }
    }

    @AfterPermissionGranted(1001)
    public void onPermissionFinished() {
        List<String> permissions = new ArrayList<>();
        permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        if (EasyPermissions.hasPermissions(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
            startAppService();
        } else if (EasyPermissions.somePermissionPermanentlyDenied(this, permissions)){
            Tools.showToast("您拒绝了该权限，可能引起APP无法正常使用，如果需要，请去设置中打开");
//            new AppSettingsDialog.Builder(this).build().show();
        } else {
            checkPermissions();
        }
    }

    private void startAppService() {
        Intent intent = new Intent(this, AppStartService.class);
        startService(intent);
    }

    private void requestUserInfo() {
        RemoteDataService.getUserInfo(new IDataCallBack() {
            @Override
            public boolean onReceiveError(int httpId, int errorCode, String errorMsg) {
                return true;
            }

            @Override
            public void onDataRefresh(int httpId, Object responseBean) {
                CommonBean<User> bean = (CommonBean<User>) responseBean;
                if (bean.resCode == HttpConstants.CODE_SUCCESS) {
                    TjadApplication.getInstance().getSession().setUserInfo(bean.result);
                }
            }
        });
    }

    private void initFragments() {
        fragmentList = new ArrayList<>();
        fragmentList.add(new DocumentFragment());
        fragmentList.add(new DesignTabFragment());
        fragmentList.add(getConstructFragment());
        fragmentList.add(new SettingFragment());
    }

    private Fragment getConstructFragment() {
        FragmentContainer constructContainer = new FragmentContainer();
        String constructMenu = ConfigReader.read(R.raw.construction_menu);
        ArrayList<PageMenu> pageMenus = (ArrayList<PageMenu>) JsonUtils.parseArray(constructMenu, PageMenu.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(Keys.PAGE_MEMU, pageMenus);
        bundle.putString(Keys.TITLE, "施工");
        Bundle args = new Bundle();
        args.putString(Keys.PAGE_ID, PageId.CONSTRUCTION_MENU);
        args.putBundle(Keys.PAGE_ARGS, bundle);
        constructContainer.setArguments(args);
        return constructContainer;
    }

    private void registerNetworkReceiver() {
        networkStatusReceiver = new NetworkStatusReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(networkStatusReceiver, filter);
    }

    public void openQrcodeScan() {
        IntentIntegrator integrator = new IntentIntegrator(this);
        integrator.setOrientationLocked(false);
        integrator.initiateScan();
    }

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            Fragment showFragment = null;
            switch (item.getItemId()) {
//                case R.id.home_tab_1:
//                    showFragment = fragmentList.get(0);
//                    break;
                case R.id.home_tab_2:
                    showFragment = fragmentList.get(0);
                    break;
                case R.id.home_tab_3:
                    showFragment = fragmentList.get(1);
                    break;
                case R.id.home_tab_4:
                    showFragment = fragmentList.get(2);
                    break;
                case R.id.home_tab_5:
                    showFragment = fragmentList.get(3);
                    break;
            }
            if (showFragment != null) {
                if (currentDisplayFragment != null) {
                    transaction.hide(currentDisplayFragment);
                }
                if (!fragmentManager.getFragments().contains(showFragment)) {
                    transaction.add(R.id.fragment_container, showFragment);
                }
                transaction.show(showFragment);
                transaction.commitAllowingStateLoss();
                currentDisplayFragment = showFragment;
            }
            return true;
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            String content = result.getContents();
            if (content != null) {
                try {
                    String[] parts = content.split("#");
                    Uri uri = Uri.parse(parts[parts.length - 1]);
                    String constructionId = uri.getLastPathSegment();
                    int constructionIdInt = Integer.parseInt(constructionId);
                    Bundle bundle = new Bundle();
                    bundle.putInt(Keys.CONSTRUCTION_ID, constructionIdInt);
                    RouteUtils.toPage(this, PageId.CONSTRUCTION_DETAIL, bundle);
                } catch (Exception e) {
                    e.printStackTrace();
                    Tools.showToast("无法识别扫描结果");
                }
            }
        }
    }

    @Override
    public void onBackPressed() {
        if (!BackHandlerHelper.handleBackPress(this)) {
            exitAppManager.onBackClick();
        }
    }

    @Override
    public void onExitAppTriggered() {
        finish();
        Process.killProcess(Process.myPid());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(networkStatusReceiver);
    }
}
